<?php

class QRcodeHelper {

    const QRCODE_SIZE = 6;
    const QRCODE_MARGIN = 2;

    /**
     * init
     */
    private static function _init() {
        
        require_once dirname(__FILE__).'/phpqrcode/qrlib.php';
    }

    /**
     * 生成 qrcode
     * @param type $text
     * @param type $savePath
     * @return bool
     */
    public static function createSimple($text, $savePath) {

        self::_init();

        QRcode::png($text, $savePath, QR_ECLEVEL_H, self::QRCODE_SIZE, self::QRCODE_MARGIN);
        return FS::isFile($savePath) ? true : false;
    }

    /**
     * 根据指定文本生成二维码，可以同时指定一个图标作为中间 logo
     * @param type $text
     * @param type $logoFile
     * @param type $savePath
     */
    public static function createWithLogo($text, $logoFile, $savePath) {

        $ret = self::createSimple($text, $savePath);
        if (!$ret) {
            return false;
        }

        $qrIm = Image::factory('GD');
        $qrIm->loadFromFile($savePath);
        $width = $qrIm->getWidth();
        $height = $qrIm->getHeight();

        $w = intval($width / 5);
        $h = intval($height / 5);
        $px = intval(2 * $width / 5);
        $py = intval(2 * $height / 5);

        $logoIm = Image::factory('GD');
        $logoIm->loadFromFile($logoFile);
        $logoIm->resize($w, $h, Image::RESIZE_STRETCH);

        $qrIm->merge($logoIm, $px, $py, $w, $h);
        $qrIm->output(Image::OUTPUT_FILE, ['file' => $savePath]);

        return FS::isFile($savePath) ? true : false;
    }
}